﻿using DemountCIM.Framework.DataBase;
using DemountCIM.Framework.PLC;
using DemountCIM.Framework.Scan;
using DemountCIM.Framework.SECSGEM;
using DemountCIM.Framework.DataBase.Table;
using WFStandard.WFThread;
using WpfUIDLL.MessageBox;
using Def = CommonLibrary.WFFile.SysDef;
using DemountCIM.ViewHelper;
using System.Collections.Concurrent;
using CommonLibrary.WFFile;
using System.Diagnostics;
using System.Security.Cryptography;
using KingExGEM;
using Newtonsoft.Json.Bson;
using DeMountCIM.Framework.RFID;
using DeMountCIM.Framework;
using static Dm.net.buffer.ByteArrayBuffer;
using System.Security.Policy;
using System.Windows.Interop;
using DeMountCIM.Windows;
using System.Windows.Markup;
using System;
using System.Reflection;
namespace DemountCIM.Framework
{
    public class MachineCtrl
    {
        private static MachineCtrl machineCtrl;                                 // 全局对象

        #region 枚举数据

        protected enum DemounterSteps
        {
            Demounter_WaitWorkStart = 0,
            Demounter_RFIDRead,
            Demounter_Load,
            Demounter_Unload,
            Demounter_WorkEnd
        }

        protected enum PalletizingSteps
        {
            Palletizing_WaitWorkStart = 0,
            Palletizing_RFIDRead,
            Palletizing_Load,
            Palletizing_Unload,
            Palletizing_WorkEnd
        }

        protected enum RemoveGlueSteps
        {
            RemoveGlue_WaitWorkStart = 0,
            RemoveGlue_Load,
            RemoveGlue_Unload,
            RemoveGlue_WorkEnd
        }

        protected enum CleaningSteps
        {
            Cleaning_WaitWorkStart = 0,
            Cleaning_Load,
            Cleaning_Unload,
            Cleaning_WorkEnd
        }

        public enum AMRBeamSteps
        {
            AMRBeam_WaitWorkStart = 0,
            AMRBeam_WaitRequest,
            AMRBeam_StartLoad,
            AMRBeam_CartLoadFinish,
            AMRBeam_StartUnload,
            AMRBeam_CartUnloadFinish,
            AMRBeam_WorkEnd
        }

        public enum AMRPlateSteps
        {
            AMRPlate_WaitWorkStart = 0,
            AMRPlate_WaitRequest,
            AMRPlate_WaitLoad,
            AMRPlate_CartLoadFinish,
            AMRPlate_WaitUnload,
            AMRPlate_CartUnloadFinish,
            AMRPlate_WorkEnd
        }

        #endregion

        // 【MES使用】
        private bool mesEN;                                                     // 启用MES
        private string mesConfigPath;                                           // 配置文件目录
        private EquipmentState prevEquipmentState;                              // 上一次的设备状态
        private PortTransferState preBeamTransferState;                         // 上一次的AMR调度状态
        private PortTransferState prePlate1TransferState;                       // 上一次的AMR调度状态
        private PortTransferState prePlate2TransferState;                       // 上一次的AMR调度状态
        private PortAccessMode[] preAccessMode;                                   // 上一次的端口手自动状态
        //private PortAccessMode[] curAccessMode;                                   // 当前的端口手自动状态
        private bool[] arriveUploadStatus;                                          // 晶托到位上传状态
        private bool[] rfidUploadStatus;                                            // rfid上传状态

        private S7Plc plcClient;                                                // PLC客户端
        private string plcIp;                                                   // plc IP
        private int plcPort;                                                    // plc 端口
        private PlcData plcDataLoad;                                            // PLC数据上料使用
        private PlcData plcData;                                                // PLC数据
        private PlcData plcDataUnload;                                          // PLC数据下料使用


        private DTE104Client[] dTE104Client;                                    // rfid读写操作类
        private string[] rfidIP;                                                // rfid IP
        private int[] rfidPort;                                                 // rfid 端口


        private object nextDemounter1Step;                                        // 晶托脱胶机运行步骤
        private object nextDemounter2Step;                                        // 晶托脱胶机运行步骤
        private object nextPalletizingStep;                                      // 树脂板码垛运行步骤
        private object nextRemoveGlueStep;                                       // 晶托铲胶运行步骤
        private object nextCleaningStep;                                         // 晶托清洗运行步骤
        protected object nextAMRBeamStep;
        protected object nextAMRPlate1Step;
        protected object nextAMRPlate2Step;


        private BaseThreadEx threadDemounter1;                                   // 晶托脱胶线程
        private BaseThreadEx threadDemounter2;                                   // 晶托脱胶线程
        private BaseThreadEx threadPalletizing;                                 // 树脂板码垛线程
        private BaseThreadEx threadRemoveGlue;                                  // 晶托铲胶线程
        private BaseThreadEx threadCleaning;                                    // 晶托清洗线程
        private BaseThreadEx threadAMRBeam;                                     // AMR下树脂板
        private BaseThreadEx threadAMRPlate1;                                    // AMR上晶托
        private BaseThreadEx threadAMRPlate2;                                    // AMR上晶托

        private BaseThreadEx threadTest;

        private bool amrtest1;
        private bool amrtest2;
        private bool amrtest3;


        #region 属性

        public string MesConfigPath { get => mesConfigPath; }
        public string Demounter1PlateID { get; private set; }
        public string Demounter2PlateID { get; private set; }
        public string PalletizingPlateID { get; private set; }
        public string RemoveGluePlateID { get; private set; }
        public string CleaningPlateID { get; private set; }
        public ConcurrentBag<string> PlateIDCleaningIn { get; private set; }      // 清洗机的晶托缓存
        public ConcurrentBag<string> PlateIDCleaningOut { get; private set; }      // 清洗机的晶托缓存

        public string Demounter1RunMsg { get; private set; }
        public string Demounter2RunMsg { get; private set; }
        public string PalletizingRunMsg { get; private set; }
        public string RemoveGlueRunMsg { get; private set; }
        public string CleaningRunMsg { get; private set; }
        public string AMRBeamRunMsg { get; private set; }
        public string AMRPlate1RunMsg { get; private set; }
        public string AMRPlate2RunMsg { get; private set; }

        public AMRPlateSteps AutoAMRPlate1Step { get => (AMRPlateSteps)nextAMRPlate1Step; }
        public AMRPlateSteps AutoAMRPlate2Step { get => (AMRPlateSteps)nextAMRPlate2Step; }
        public AMRBeamSteps AutoAMRBeamStep { get => (AMRBeamSteps)nextAMRBeamStep; }

        #endregion

        public MachineCtrl()
        {
            // MES 2025/3/27
            mesConfigPath = "System\\DemounterConfig\\DemounterConfig.kgprj";
            preAccessMode = new PortAccessMode[3];
            arriveUploadStatus = new bool[4];
            rfidUploadStatus = new bool[4];

            this.dTE104Client = new DTE104Client[(int)RFIDDef.RFIDGatewayCount];
            this.rfidIP = new string[(int)RFIDDef.RFIDGatewayCount];
            this.rfidPort = new int[(int)RFIDDef.RFIDGatewayCount];

            this.rfidIP[0] = "192.168.1.91";
            this.rfidIP[1] = "192.168.1.95";
            for (int i = 0; i < (int)RFIDDef.RFIDGatewayCount; i++)
            {
                this.dTE104Client[i] = new DTE104Client();
                this.rfidPort[i] = 33000;
            }

            this.plcIp = "192.168.0.200";
            this.plcPort = 502;
            this.plcData = new PlcData();
            this.plcDataLoad = new PlcData();
            this.plcDataUnload = new PlcData();

            PlateIDCleaningIn = new ConcurrentBag<string>();
            PlateIDCleaningOut = new ConcurrentBag<string>();

            Demounter1PlateID = "";
            Demounter2PlateID = "";
            PalletizingPlateID = "";
            RemoveGluePlateID = "";
            CleaningPlateID = "";

            // 初始化步骤
            this.nextDemounter1Step = DemounterSteps.Demounter_WaitWorkStart;
            this.nextDemounter2Step = DemounterSteps.Demounter_WaitWorkStart;
            this.nextPalletizingStep = PalletizingSteps.Palletizing_WaitWorkStart;
            this.nextRemoveGlueStep = RemoveGlueSteps.RemoveGlue_WaitWorkStart;
            this.nextCleaningStep = CleaningSteps.Cleaning_WaitWorkStart;
            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_WaitWorkStart;
            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WaitWorkStart;
            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WaitWorkStart;
            this.threadDemounter1 = new BaseThreadEx(Demounter1Thread);
            this.threadDemounter2 = new BaseThreadEx(Demounter2Thread);
            this.threadPalletizing = new BaseThreadEx(PalletizingThread);
            this.threadRemoveGlue = new BaseThreadEx(RemoveGlueThread);
            this.threadCleaning = new BaseThreadEx(CleaningThread);
            this.threadAMRBeam = new BaseThreadEx(BeamUnloadThread);
            this.threadAMRPlate1 = new BaseThreadEx(PlateLoadThread1);
            this.threadAMRPlate2 = new BaseThreadEx(PlateLoadThread2);

            this.threadTest = new BaseThreadEx(TestThread);

            var parameterRepository = DataBaseContainer.GetInstance().GetParameterRepository();
            // 常规参数
            parameterRepository.InsertPrivateParam(1, "mes_en", "启用SECS/GEM", "开启SECS/GEM并与HOST连接传输数据", DataBase.Table.ParamType.Bool, DataBase.Table.UserLevel.工程师);
            // 系统参数
            parameterRepository.InsertPrivateParam(3, "plc_ip", "PLC IP", "设置PLC的访问IP地址，例：“192.168.1.10”", DataBase.Table.ParamType.String, DataBase.Table.UserLevel.管理员);
            parameterRepository.InsertPrivateParam(3, "plc_port", "PLC端口", "设置PLC的访问端口号，例：“502”", DataBase.Table.ParamType.Int, DataBase.Table.UserLevel.管理员);

            parameterRepository.InsertPrivateParam(3, "rfid_ip[0]", "RFID网关#1#IP", "设置RFID网关#1#的访问IP地址，例：“192.168.1.11”", ParamType.String, UserLevel.管理员);
            parameterRepository.InsertPrivateParam(3, "rfid_port[0]", "RFID网关#1#端口", "设置RFID网关#1#的访问端口号，例：“33000”", ParamType.Int, UserLevel.管理员);
            parameterRepository.InsertPrivateParam(3, "rfid_ip[1]", "RFID网关#2#IP", "设置RFID网关#2#的访问IP地址，例：“192.168.1.12”", ParamType.String, UserLevel.管理员);
            parameterRepository.InsertPrivateParam(3, "rfid_port[1]", "RFID网关#2#端口", "设置RFID网关#2#的访问端口号，例：“33000”", ParamType.Int, UserLevel.管理员);


            parameterRepository.InsertPrivateParam(3, "mes_config_path", "MES配置路径", "MES配置文件路径，例：“System\\DemounterConfig\\DemounterConfig.kgprj”，MES客户端需要重新初始化才能成效", DataBase.Table.ParamType.String, DataBase.Table.UserLevel.管理员);
            ReadDBParam();
        }

        public void Initialize()
        {
            // 初始化界面
            InitWindow initPage = new InitWindow();
            initPage.Show();

            initPage.AddInfo("开始初始化...");


            // 创建客户端
            this.plcClient = new S7Plc(plcIp, plcPort, 0, 0);

            // 连接MES
            if (KingEQP.GetInstance().KingInitialize(mesConfigPath))
            {
                KingEQP.GetInstance().KingStart();
            }

            // 连接PLC
            if (!Def.IsNoHardware() && !this.plcClient.IsConnected())
            {
                string strErrInfo = "";
                this.plcClient.Connect(ref strErrInfo);
            }

            #region RFID初始化

            for (int nIdx = 0; nIdx < (int)RFIDDef.RFIDGatewayCount; nIdx++)
            {
                if (!Def.IsNoHardware() && !this.dTE104Client[nIdx].IsConnected())
                {
                    if (this.dTE104Client[nIdx].Connect(rfidIP[nIdx], rfidPort[nIdx]))
                    {


                    }
                }
            }


            #region TEST
            //if (this.dTE104Client[0].Connect(rfidIP[0], rfidPort[0]))
            //{
            //    string data = "";

            //    RfidReadCarrierID(2, out data);
            //dTE104Client[0].ReadCarrierID(1, out data);
            //    Console.WriteLine(data);
            //}
            #endregion



            #endregion

            initPage.AddInfo("初始化完成！");

            Thread.Sleep(500);

            initPage.Hide();
            initPage.Close();

            //this.threadTest.InitThread("测试");
            //this.threadTest.StartTime = DateTime.Now;

            //this.threadDemounter1.InitThread("脱胶机1");
            //this.threadDemounter1.StartTime = DateTime.Now;

            //this.threadDemounter2.InitThread("脱胶机2");
            //this.threadDemounter2.StartTime = DateTime.Now;

            //this.threadPalletizing.InitThread("树脂板码垛");
            //this.threadPalletizing.StartTime = DateTime.Now;

            //this.threadRemoveGlue.InitThread("铲胶机");
            //this.threadRemoveGlue.StartTime = DateTime.Now;

            //this.threadCleaning.InitThread("清洗机");
            //this.threadCleaning.StartTime = DateTime.Now;

            //this.threadAMRBeam.InitThread("树脂板下料");
            //this.threadAMRBeam.StartTime = DateTime.Now;

            //this.threadAMRPlate1.InitThread("晶托上料1");
            //this.threadAMRPlate1.StartTime = DateTime.Now;
            //this.threadAMRPlate2.InitThread("晶托上料2");
            //this.threadAMRPlate2.StartTime = DateTime.Now;

        }

        /// <summary>
        /// 获取全局对象
        /// </summary>
        /// <returns></returns>
        public static MachineCtrl GetInstance()
        {
            if (null == machineCtrl)
            {
                machineCtrl = new MachineCtrl();
            }
            return machineCtrl;
        }

        /// <summary>
        /// 读取参数
        /// </summary>
        public void ReadDBParam()
        {
            var parameterRepository = DataBaseContainer.GetInstance().GetParameterRepository();

            mesEN = parameterRepository.ReadBool("mes_en", false);
            plcIp = parameterRepository.ReadString("plc_ip", plcIp);
            plcPort = parameterRepository.ReadInt("plc_port", plcPort);

            for (int i = 0; i < (int)RFIDDef.RFIDGatewayCount; i++)
            {
                rfidIP[i] = parameterRepository.ReadString($"rfid_ip[{i}]", rfidIP[i]);
                rfidPort[i] = parameterRepository.ReadInt($"rfid_port[{i}]", rfidPort[i]);
            }

            mesConfigPath = parameterRepository.ReadString("mes_config_path", mesConfigPath);
        }

        public void Dispose()
        {
            if (null != threadDemounter1)
            {
                this.threadDemounter1.ReleaseThread();
            }
            if (null != threadPalletizing)
            {
                this.threadPalletizing.ReleaseThread();
            }
            if (null != threadRemoveGlue)
            {
                this.threadRemoveGlue.ReleaseThread();
            }
            if (null != threadCleaning)
            {
                this.threadCleaning.ReleaseThread();
            }
            if (null != threadAMRBeam)
            {
                this.threadAMRBeam.ReleaseThread();
            }
            if (null != threadAMRPlate1)
            {
                this.threadAMRPlate1.ReleaseThread();
            }
            if (null != threadAMRPlate2)
            {
                this.threadAMRPlate2.ReleaseThread();
            }

            // 断开PLC连接
            if (null != this.plcClient)
            {
                string strErrInfo = "";
                this.plcClient.Disconnect(ref strErrInfo);
            }
        }

        #region 自动化线程

        private void TestThread()
        {
            Thread.Sleep(3000);





            //KingEQP.GetInstance().KingeqOfflineState();
            //KingEQP.GetInstance().KingLocal();
            //KingEQP.GetInstance().KingRemote();

            //MesChangeEquipmentState(EquipmentState.Production);

            //MesSetAlarm(1);
            //MesClearAlarm(1);

            string plateID = "JT1001";
            string glueQrCode1 = "QC10001";
            string glueQrCode2 = "QC10002";
            string beamQrcode = "BEAM10001";


            //MesPlateOnloadStation(plateID, 1);

            //MesPlateReadRFID1(plateID);

            //MesPlateRcmdSuccessful(plateID);

            //MesPlateRcmdFailed(plateID);

            //MesPlateArriveDemounterStation(plateID, 1);
            //MesPlateLeaveDemounterStation(plateID, 2);

            //MesPlateArrivePalletizingStation(plateID, 1);
            //MesPlateLeavePalletizingStation(plateID, 2);

            //  MesPlateReadRFID2(plateID);

            //MesPlateArriveRemoveGlueStation(plateID, 1);
            //MesPlateLeaveRemoveGlueStation(plateID, 2);

            //MesPlateArriveCleaningStation(plateID, 1);
            //MesPlateLeaveCleaningStation(plateID, 2);

            //MesPortTransferStateChange(1, 3, 1);

            //MesPortTransferStateChange(1, 5, 3);


            //MesCartLoadComplete();

            //MesPortTransferStateChange(1, 4, 5);

            //MesPortTransferStateChange(1, 5, 4);

            // MesCartUnloadComplete();

            //MesPortTransferStateChange(1, 5, 3);

            //MesPlateWriteRFID(plateID);


            // 废树脂板下料
            //MesPortTransferStateChange(3,"U", 3, 1);

            //MesPortTransferStateChange(3, "U", 5, 3);


            //MesCartLoadComplete(3, "U");

            //MesPortTransferStateChange(3, "U", 4, 5);

            //MesPortTransferStateChange(3, "U", 5, 4);

            //MesCartUnloadComplete(3, "U");

            //MesPortTransferStateChange(3, "U", 5, 3);

            //MesBeamUnloadStation(3, "U", plateID);
        }

        /// <summary>
        /// 脱胶机#1
        /// </summary>
        private void Demounter1Thread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }

            //if (RfidIsConnected(1))
            //{
            //    Thread.Sleep(1000);
            //    if (RfidReadCarrierID(1, out string plateID))
            //    {

            //    }
            //    else
            //    {

            //    }
            //}

            try
            {
                plcClient.ReadPlcData(ref plcDataLoad);
                switch (nextDemounter1Step)
                {
                    case DemounterSteps.Demounter_WaitWorkStart:
                        {
                            Demounter1RunMsg = "等待开始信号";
                            if (Def.IsNoHardware())
                            {
                                Random random = new Random();
                                Demounter1PlateID = $"JT{random.Next(100)}";
                                this.nextDemounter1Step = DemounterSteps.Demounter_RFIDRead;
                            }
                            else if (!MesIsConnected())
                            {
                                return;
                            }
                            else if (plcDataLoad.demounter1Station[0] && !plcDataLoad.demounter1Station[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID1(false, ref msg);
                            }
                            else if (plcDataLoad.demounter1Station[1])
                            {
                                if (!arriveUploadStatus[0])
                                {
                                    MesPlateOnloadStation("", 1);
                                    arriveUploadStatus[0] = true;
                                }

                                if (Def.IsNoHardware() || RfidIsConnected(0))
                                {

                                    if (RfidReadCarrierID(1, out string plateID))
                                    {
                                        plateID = plateID.Replace("\0", "");

                                        if (!rfidUploadStatus[0])
                                        {
                                            MesPlateReadRFID1(plateID);
                                            rfidUploadStatus[0] = true;
                                        }
                                        var result = KingEQP.GetInstance().GetRfidStatus(plateID);

                                        if (result == 1)
                                        {
                                            Demounter1PlateID = plateID;

                                            string msg = "";
                                            plcClient.ReadFinishRFID1(true, ref msg);
                                            this.nextDemounter1Step = DemounterSteps.Demounter_RFIDRead;
                                        }
                                        else if (result == 2)
                                        {
                                            // 报警不允许动作
                                            ShowMsgBox.ShowDialog($"MES不允许【{plateID}】进入！", MessageType.MsgWarning);
                                        }
                                    }
                                    else
                                    {
                                        ShowMsgBox.ShowDialog($"脱胶机#1#读取RFID芯片失败！请检查RFID硬件{plateID}", MessageType.MsgWarning);

                                        //if (!rfidUploadStatus[0])
                                        //{
                                        //    MesPlateReadRFID1("");
                                        //    rfidUploadStatus[0] = true;
                                        //}

                                        //var result = KingEQP.GetInstance().GetRfidStatus(1);

                                        //if (result == 1)
                                        //{
                                        //    Demounter1PlateID = "";

                                        //    string msg = "";
                                        //    plcClient.ReadFinishRFID1(true, ref msg);
                                        //    this.nextDemounter1Step = DemounterSteps.Demounter_RFIDRead;
                                        //}
                                        //else if (result == 2)
                                        //{
                                        //    // 报警不允许动作

                                        //    ShowMsgBox.ShowDialog("脱胶机#1#读取RFID芯片失败！请检查RFID硬件", MessageType.MsgWarning);
                                        //}

                                    }
                                }
                                else
                                {
                                    ShowMsgBox.ShowDialog("请连接RFID网关！", MessageType.MsgWarning);
                                }
                            }

                            break;
                        }
                    case DemounterSteps.Demounter_RFIDRead:
                        {
                            Demounter1RunMsg = "读取RFID芯片信息";

                            rfidUploadStatus[0] = false;
                            arriveUploadStatus[0] = false;

                            Thread.Sleep(500);

                            if (Def.IsNoHardware() || !plcDataLoad.demounter1Station[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID1(false, ref msg);



                                this.nextDemounter1Step = DemounterSteps.Demounter_Load;
                            }

                            break;
                        }
                    case DemounterSteps.Demounter_Load:
                        {
                            Demounter1RunMsg = "晶托进入脱胶机";

                            MesPlateArriveDemounterStation(Demounter1PlateID, plcDataLoad.demounter1State);

                            this.nextDemounter1Step = DemounterSteps.Demounter_Unload;

                            break;
                        }
                    case DemounterSteps.Demounter_Unload:
                        {
                            Demounter1RunMsg = "晶托离开脱胶机";

                            if (Def.IsNoHardware() || plcDataLoad.demounter1Station[2])
                            {
                                MesPlateLeaveDemounterStation(Demounter1PlateID, plcDataLoad.demounter1State);

                                this.nextDemounter1Step = DemounterSteps.Demounter_WorkEnd;

                            }
                            break;
                        }
                    case DemounterSteps.Demounter_WorkEnd:
                        {
                            Demounter1RunMsg = "等待工作完成";

                            Demounter1PlateID = string.Empty;

                            this.nextDemounter1Step = DemounterSteps.Demounter_WaitWorkStart;
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Demounter1Thread-{this.nextDemounter1Step}：{ex.Message}");
            }
        }

        /// <summary>
        /// 脱胶机#2
        /// </summary>
        private void Demounter2Thread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }

            try
            {
                plcClient.ReadPlcData(ref plcDataLoad);
                switch (nextDemounter2Step)
                {
                    case DemounterSteps.Demounter_WaitWorkStart:
                        {
                            Demounter2RunMsg = "等待开始信号";
                            if (Def.IsNoHardware())
                            {
                                Random random = new Random();
                                Demounter2PlateID = $"JT{random.Next(100)}";
                                this.nextDemounter2Step = DemounterSteps.Demounter_RFIDRead;
                            }
                            else if (!MesIsConnected())
                            {
                                return;
                            }
                            else if (plcDataLoad.demounter2Station[0] && !plcDataLoad.demounter2Station[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID2(false, ref msg);
                            }
                            else if (plcDataLoad.demounter2Station[1])
                            {

                                if (!arriveUploadStatus[1])
                                {
                                    MesPlateOnloadStation2("");
                                    arriveUploadStatus[1] = true;
                                }


                                if (RfidIsConnected(1))
                                {
                                    if (RfidReadCarrierID(2, out string plateID))
                                    {
                                        plateID = plateID.Replace("\0", "");
                                        if (!rfidUploadStatus[1])
                                        {
                                            MesPlateReadRFID2(plateID);
                                            rfidUploadStatus[1] = true;
                                        }
                                        var result = KingEQP.GetInstance().GetRfidStatus(plateID);
                                        if (result == 1)
                                        {
                                            string msg = "";
                                            plcClient.ReadFinishRFID2(true, ref msg);

                                            Demounter2PlateID = plateID;

                                            this.nextDemounter2Step = DemounterSteps.Demounter_RFIDRead;
                                        }
                                        else if (result == 2)
                                        {
                                            // 报警不允许动作
                                            ShowMsgBox.ShowDialog($"脱胶机#2#MES不允许【{plateID}】离开！", MessageType.MsgWarning);
                                        }
                                    }
                                    else
                                    {
                                        ShowMsgBox.ShowDialog("脱胶机#2#读取RFID芯片失败！请检查RFID硬件", MessageType.MsgWarning);

                                        //if (!rfidUploadStatus[1])
                                        //{
                                        //    MesPlateReadRFID2("");
                                        //    rfidUploadStatus[1] = true;
                                        //}

                                        //var result = KingEQP.GetInstance().GetRfidStatus(2);

                                        //if (result == 1)
                                        //{
                                        //    Demounter2PlateID = "";

                                        //    string msg = "";
                                        //    plcClient.ReadFinishRFID2(true, ref msg);
                                        //    this.nextDemounter2Step = DemounterSteps.Demounter_RFIDRead;
                                        //}
                                        //else if (result == 2)
                                        //{
                                        //    // 报警不允许动作

                                        //    ShowMsgBox.ShowDialog("脱胶机#2#读取RFID芯片失败！请检查RFID硬件", MessageType.MsgWarning);
                                        //}

                                    }
                                }
                                else
                                {
                                    ShowMsgBox.ShowDialog("请连接RFID网关！", MessageType.MsgWarning);
                                }
                            }

                            break;
                        }
                    case DemounterSteps.Demounter_RFIDRead:
                        {
                            Demounter2RunMsg = "读取RFID芯片信息";


                            arriveUploadStatus[1] = false;
                            rfidUploadStatus[1] = false;

                            this.nextDemounter2Step = DemounterSteps.Demounter_Load;
                            break;
                        }
                    case DemounterSteps.Demounter_Load:
                        {
                            Demounter2RunMsg = "晶托进入脱胶机";
                            if (!plcDataLoad.demounter2Station[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID2(false, ref msg);
                                MesPlateArriveDemounter2Station(Demounter2PlateID, plcDataLoad.demounter2State);

                                this.nextDemounter2Step = DemounterSteps.Demounter_Unload;
                            }

                            break;
                        }
                    case DemounterSteps.Demounter_Unload:
                        {
                            Demounter2RunMsg = "晶托离开脱胶机";

                            if (Def.IsNoHardware() || plcDataLoad.demounter2Station[2])
                            {
                                MesPlateLeaveDemounter2Station(Demounter2PlateID, plcDataLoad.demounter2State);

                                this.nextDemounter2Step = DemounterSteps.Demounter_WorkEnd;

                            }
                            break;
                        }
                    case DemounterSteps.Demounter_WorkEnd:
                        {
                            Demounter2RunMsg = "等待工作完成";

                            Demounter2PlateID = string.Empty;

                            this.nextDemounter2Step = DemounterSteps.Demounter_WaitWorkStart;
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Demounter2Thread-{this.nextDemounter2Step}：{ex.Message}");
            }
        }

        /// <summary>
        /// 树脂板码垛
        /// </summary>
        private void PalletizingThread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }
            plcClient.ReadPlcData(ref plcDataLoad);
            try
            {

                switch (nextPalletizingStep)
                {
                    case PalletizingSteps.Palletizing_WaitWorkStart:
                        {
                            PalletizingRunMsg = "等待开始信号";

                            if (MesIsConnected())
                            {
                                this.nextPalletizingStep = PalletizingSteps.Palletizing_RFIDRead;
                            }
                            break;
                        }
                    case PalletizingSteps.Palletizing_RFIDRead:
                        {
                            PalletizingRunMsg = "读取RFID芯片信息";

                            if (Def.IsNoHardware())
                            {
                                Random random = new Random();
                                PalletizingPlateID = $"JT{random.Next(100)}";
                                this.nextPalletizingStep = PalletizingSteps.Palletizing_Load;
                            }
                            else if (plcDataLoad.palletizingStation[0] && !plcDataLoad.palletizingStation[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID3(false, ref msg);
                            }
                            else if (plcDataLoad.palletizingStation[1])
                            {


                                if (RfidIsConnected(1))
                                {
                                    if (RfidReadCarrierID(3, out string plateID))
                                    {
                                        plateID = plateID.Replace("\0", "");
                                        if (!rfidUploadStatus[2])
                                        {
                                            MesPlateReadRFID3(plateID);
                                            rfidUploadStatus[2] = true;
                                        }


                                        var result = KingEQP.GetInstance().GetRfidStatus(plateID);

                                        if (result == 1)
                                        {
                                            string msg = "";
                                            plcClient.ReadFinishRFID3(true, ref msg);

                                            PalletizingPlateID = plateID;

                                            if (!arriveUploadStatus[2])
                                            {
                                                MesPlateArrivePalletizingStation(plateID, plcDataLoad.palletizingState);
                                                arriveUploadStatus[2] = true;
                                            }

                                            this.nextPalletizingStep = PalletizingSteps.Palletizing_Load;
                                        }
                                        else if (result == 2)
                                        {
                                            // 报警不允许动作
                                            ShowMsgBox.ShowDialog($"MES不允许【{plateID}】进入！", MessageType.MsgWarning);
                                        }



                                    }
                                    else
                                    {
                                        ShowMsgBox.ShowDialog($"树脂板读取RFID芯片失败！请检查RFID硬件【{plateID}】", MessageType.MsgWarning);

                                        //if (!rfidUploadStatus[2])
                                        //{
                                        //    MesPlateReadRFID3("");
                                        //    rfidUploadStatus[2] = true;
                                        //}

                                        //var result = KingEQP.GetInstance().GetRfidStatus(3);

                                        //if (result == 1)
                                        //{
                                        //    PalletizingPlateID = "";

                                        //    string msg = "";
                                        //    plcClient.ReadFinishRFID3(true, ref msg);
                                        //    this.nextPalletizingStep = PalletizingSteps.Palletizing_Load;
                                        //}
                                        //else if (result == 2)
                                        //{
                                        //    // 报警不允许动作

                                        //    ShowMsgBox.ShowDialog("树脂板读取RFID芯片失败！请检查RFID硬件", MessageType.MsgWarning);
                                        //}
                                    }
                                }
                                else
                                {
                                    ShowMsgBox.ShowDialog("请连接RFID网关！", MessageType.MsgWarning);
                                }
                            }
                            break;
                        }
                    case PalletizingSteps.Palletizing_Load:
                        {
                            PalletizingRunMsg = "晶托进入树脂板码垛工位";

                            arriveUploadStatus[2] = false;
                            rfidUploadStatus[2] = false;

                            if (Def.IsNoHardware() || !plcDataLoad.palletizingStation[1])
                            {
                                string msg = "";
                                plcClient.ReadFinishRFID3(false, ref msg);


                                this.nextPalletizingStep = PalletizingSteps.Palletizing_Unload;
                            }
                            break;
                        }
                    case PalletizingSteps.Palletizing_Unload:
                        {
                            PalletizingRunMsg = "晶托离开树脂板码垛工位";

                            if (Def.IsNoHardware() || plcDataLoad.palletizingStation[2])
                            {
                                MesPlateLeavePalletizingStation(PalletizingPlateID, plcDataLoad.palletizingState);
                                this.nextPalletizingStep = PalletizingSteps.Palletizing_WorkEnd;
                            }
                            break;
                        }
                    case PalletizingSteps.Palletizing_WorkEnd:
                        {
                            PalletizingRunMsg = "等待工作完成";

                            RemoveGluePlateID = PalletizingPlateID;
                            PalletizingPlateID = string.Empty;

                            this.nextPalletizingStep = PalletizingSteps.Palletizing_WaitWorkStart;
                            break;
                        }
                }

            }
            catch (Exception ex)
            {
                Trace.WriteLine($"PalletizingThread-{this.nextPalletizingStep}：{ex.Message}");
            }
        }

        /// <summary>
        /// 铲胶机
        /// </summary>
        private void RemoveGlueThread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }

            Thread.Sleep(300);

            plcClient.ReadPlcData(ref plcDataUnload);
            try
            {
                switch (nextRemoveGlueStep)
                {
                    case RemoveGlueSteps.RemoveGlue_WaitWorkStart:
                        {
                            RemoveGlueRunMsg = "等待开始信号";

                            if (MesIsConnected())
                            {
                                this.nextRemoveGlueStep = RemoveGlueSteps.RemoveGlue_Load;

                            }
                            break;
                        }
                    case RemoveGlueSteps.RemoveGlue_Load:
                        {
                            RemoveGlueRunMsg = "等待晶托进入晶托铲胶工位";


                            if (Def.IsNoHardware() || plcDataUnload.removeGlueStation[0])
                            {
                                MesPlateArriveRemoveGlueStation(RemoveGluePlateID, plcDataUnload.removeGlueState);
                                this.nextRemoveGlueStep = RemoveGlueSteps.RemoveGlue_Unload;

                            }

                            break;
                        }
                    case RemoveGlueSteps.RemoveGlue_Unload:
                        {
                            RemoveGlueRunMsg = "等待晶托离开晶托铲胶工位";


                            if (Def.IsNoHardware() || plcDataUnload.removeGlueStation[1])
                            {
                                MesPlateLeaveRemoveGlueStation(RemoveGluePlateID, plcDataUnload.removeGlueState);


                                this.nextRemoveGlueStep = RemoveGlueSteps.RemoveGlue_WorkEnd;

                            }

                            break;
                        }
                    case RemoveGlueSteps.RemoveGlue_WorkEnd:
                        {
                            RemoveGlueRunMsg = "等待工作完成";

                            PlateIDCleaningIn.Add(RemoveGluePlateID);
                            PlateIDCleaningOut.Add(RemoveGluePlateID);

                            RemoveGluePlateID = string.Empty;

                            this.nextRemoveGlueStep = RemoveGlueSteps.RemoveGlue_WaitWorkStart;
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"RemoveGlueThread-{this.nextRemoveGlueStep}：{ex.Message}");
            }
        }

        /// <summary>
        /// 清洗机
        /// </summary>
        private void CleaningThread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1400);
            }
            try
            {
                Thread.Sleep(300);

                plcClient.ReadPlcData(ref plcDataUnload);


                if (Def.IsNoHardware() || plcDataUnload.cleaningStation[0])
                {

                    this.CleaningRunMsg = "晶托进入清洗工位";

                    if (PlateIDCleaningIn.TryTake(out string res))
                    {
                        MesPlateArriveCleaningStation(res, plcDataUnload.cleaningState);
                    }
                }

                if (Def.IsNoHardware() || plcDataUnload.cleaningStation[1])
                {
                    this.CleaningRunMsg = "晶托离开清洗工位";


                    if (PlateIDCleaningOut.TryTake(out string res))
                    {
                        string msg = "";
                        plcClient.ReadFinishRFID4(false, ref msg);
                        MesPlateLeaveCleaningStation(res, plcDataUnload.cleaningState);
                    }
                }

                if (Def.IsNoHardware() || plcDataUnload.cleaningStation[2])
                {
                    this.CleaningRunMsg = "晶托到达清洗机RFID工位";

                    if (RfidIsConnected(3))
                    {

                        if (RfidReadCarrierID(4, out string plateID))
                        {
                            plateID = plateID.Replace("\0", "");

                            if (!rfidUploadStatus[3])
                            {
                                MesPlateWriteRFID(plateID);
                                rfidUploadStatus[3] = true;
                            }
                            var result = KingEQP.GetInstance().GetRfidStatus(plateID);

                            if (result == 1)
                            {
                                rfidUploadStatus[3] = false;
                                string msg = "";
                                plcClient.ReadFinishRFID4(true, ref msg);
                            }
                            else if (result == 2)
                            {
                                // 报警不允许动作
                                ShowMsgBox.ShowDialog($"MES不允许【{plateID}】进入！", MessageType.MsgWarning);
                            }
                        }
                        else
                        {
                            ShowMsgBox.ShowDialog($"清洗机读取RFID芯片失败！请检查RFID硬件【{plateID}】", MessageType.MsgWarning);



                        }
                    }
                    else
                    {
                        ShowMsgBox.ShowDialog("请连接RFID网关！", MessageType.MsgWarning);
                    }
                }


            }
            catch (Exception ex)
            {
                Trace.WriteLine($"CleaningThread-{this.nextCleaningStep}：{ex.Message}");
            }
        }

        //private void CleaningThread()
        //{
        //    if (Def.IsNoHardware())
        //    {
        //        Thread.Sleep(1400);
        //    }
        //    try
        //    {

        //        plcClient.ReadPlcData(ref plcDataUnload);

        //        switch (nextCleaningStep)
        //        {
        //            case CleaningSteps.Cleaning_WaitWorkStart:
        //                {
        //                    this.CleaningRunMsg = "等待开始信号";
        //                    this.nextCleaningStep = CleaningSteps.Cleaning_Load;
        //                    break;
        //                }

        //            case CleaningSteps.Cleaning_Load:
        //                {
        //                    this.CleaningRunMsg = "等待晶托进入清洗工位";

        //                    if (Def.IsNoHardware() || plcDataUnload.cleaningStation[0])
        //                    {
        //                        if (PlateIDCleaning.TryPeek(out string res))
        //                        {
        //                            MesPlateArriveCleaningStation(res, plcDataUnload.cleaningState);
        //                            this.nextCleaningStep = CleaningSteps.Cleaning_Unload;
        //                        }
        //                    }

        //                    break;
        //                }
        //            case CleaningSteps.Cleaning_Unload:
        //                {
        //                    this.CleaningRunMsg = "等待晶托离开清洗工位";


        //                    if (Def.IsNoHardware() || plcDataUnload.cleaningStation[1])
        //                    {
        //                        if (PlateIDCleaning.TryTake(out string res))
        //                        {
        //                            MesPlateLeaveCleaningStation(res, plcDataUnload.cleaningState);
        //                            Thread.Sleep(500);
        //                            MesPlateWriteRFID(res);
        //                        }
        //                        this.nextCleaningStep = CleaningSteps.Cleaning_WorkEnd;
        //                    }


        //                    break;
        //                }
        //            case CleaningSteps.Cleaning_WorkEnd:
        //                {
        //                    this.CleaningRunMsg = "等待工位完成";


        //                    this.nextCleaningStep = CleaningSteps.Cleaning_WaitWorkStart;

        //                    break;
        //                }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Trace.WriteLine($"CleaningThread-{this.nextCleaningStep}：{ex.Message}");
        //    }
        //}


        /// <summary>
        /// 晶托上料
        /// </summary>
        private void PlateLoadThread1()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }
            switch (nextAMRPlate1Step)
            {
                case AMRPlateSteps.AMRPlate_WaitWorkStart:
                    {
                        AMRPlate1RunMsg = "等待开始信号";

                        if (MesIsConnected())
                        {
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WaitRequest;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitRequest:
                    {
                        AMRPlate1RunMsg = "等待PLC发送请求";

                        if (Def.IsNoHardware())
                        {
                            this.nextAMRPlate1Step = !amrtest1 ? AMRPlateSteps.AMRPlate_WaitLoad : AMRPlateSteps.AMRPlate_WaitUnload;
                            return;
                        }
                        if (!plcData.plateCartArrived[0] && !plcData.plateAMRArrived[0] &&
                            plcData.plateCartLoadASK[0])
                        {
                            MesPortTransferStateChange(1, "B", PortTransferState.ReadyToLoad, prePlate1TransferState);
                            prePlate1TransferState = PortTransferState.ReadyToLoad;
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WaitLoad;
                        }
                        if (plcData.plateCartArrived[0] && !plcData.plateAMRArrived[0] &&
                            plcData.plateCartUnloadASK[0])
                        {
                            MesPortTransferStateChange(1, "B", PortTransferState.ReadyToUnload, prePlate1TransferState);
                            prePlate1TransferState = PortTransferState.ReadyToUnload;
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WaitUnload;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitLoad:
                    {
                        AMRPlate1RunMsg = "等待AMR到达上晶托工位1";
                        if (Def.IsNoHardware() || plcData.plateAMRArrived[0])
                        {
                            MesPortTransferStateChange(1, "B", PortTransferState.TransferBlocked, prePlate1TransferState);
                            prePlate1TransferState = PortTransferState.TransferBlocked;
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_CartLoadFinish;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_CartLoadFinish:
                    {
                        AMRPlate1RunMsg = "等待晶托小车上料完成";
                        if (Def.IsNoHardware() || plcData.plateCartArrived[0])
                        {
                            MesCartLoadComplete(1);
                            amrtest1 = true;

                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WorkEnd;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitUnload:
                    {
                        AMRPlate1RunMsg = "等待AMR到达上晶托工位1";
                        if (Def.IsNoHardware() || plcData.plateAMRArrived[0])
                        {
                            MesPortTransferStateChange(1, "B", PortTransferState.TransferBlocked, prePlate1TransferState);
                            prePlate1TransferState = PortTransferState.TransferBlocked;
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_CartUnloadFinish;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_CartUnloadFinish:
                    {
                        AMRPlate1RunMsg = "等待晶托小车下料完成";
                        if (!plcData.plateCartArrived[0] && !plcData.plateAMRArrived[0])
                        {
                            MesCartUnloadComplete(1, "B");
                            amrtest1 = false;
                            this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WorkEnd;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WorkEnd:
                    {
                        AMRPlate1RunMsg = "等待工作完成";

                        this.nextAMRPlate1Step = AMRPlateSteps.AMRPlate_WaitWorkStart;
                        break;
                    }
            }

        }

        private void PlateLoadThread2()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }
            switch (nextAMRPlate2Step)
            {
                case AMRPlateSteps.AMRPlate_WaitWorkStart:
                    {
                        AMRPlate2RunMsg = "等待开始信号";

                        if (MesIsConnected())
                        {
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WaitRequest;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitRequest:
                    {
                        AMRPlate2RunMsg = "等待PLC发送请求";

                        if (Def.IsNoHardware())
                        {
                            this.nextAMRPlate2Step = !amrtest2 ? AMRPlateSteps.AMRPlate_WaitLoad : AMRPlateSteps.AMRPlate_WaitUnload;
                            return;

                        }

                        if (!plcData.plateCartArrived[1] && !plcData.plateAMRArrived[1] &&
                            plcData.plateCartLoadASK[1])
                        {
                            MesPortTransferStateChange(2, "B", PortTransferState.ReadyToLoad, prePlate2TransferState);
                            prePlate2TransferState = PortTransferState.ReadyToLoad;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WaitLoad;
                        }

                        if (plcData.plateCartArrived[1] && !plcData.plateAMRArrived[1] &&
                            plcData.plateCartUnloadASK[1])
                        {
                            MesPortTransferStateChange(2, "B", PortTransferState.ReadyToUnload, prePlate2TransferState);
                            prePlate2TransferState = PortTransferState.ReadyToUnload;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WaitUnload;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitLoad:
                    {
                        AMRPlate2RunMsg = "等待AMR到达上晶托工位2";
                        if (Def.IsNoHardware() || plcData.plateAMRArrived[1])
                        {
                            MesPortTransferStateChange(2, "B", PortTransferState.TransferBlocked, prePlate2TransferState);
                            prePlate2TransferState = PortTransferState.TransferBlocked;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_CartLoadFinish;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_CartLoadFinish:
                    {
                        AMRPlate2RunMsg = "等待晶托小车上料完成";
                        if (Def.IsNoHardware() || plcData.plateCartArrived[1])
                        {
                            MesCartLoadComplete(2);
                            amrtest2 = true;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WorkEnd;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WaitUnload:
                    {
                        AMRPlate2RunMsg = "等待AMR到达上晶托工位2";
                        if (Def.IsNoHardware() || plcData.plateAMRArrived[1])
                        {
                            MesPortTransferStateChange(2, "B", PortTransferState.TransferBlocked, prePlate2TransferState);
                            prePlate2TransferState = PortTransferState.TransferBlocked;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_CartUnloadFinish;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_CartUnloadFinish:
                    {
                        AMRPlate2RunMsg = "等待晶托小车下料完成";
                        if (!plcData.plateCartArrived[1] && !plcData.plateAMRArrived[1])
                        {
                            MesCartUnloadComplete(2, "B");
                            amrtest2 = false;
                            this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WorkEnd;
                        }
                        break;
                    }
                case AMRPlateSteps.AMRPlate_WorkEnd:
                    {
                        AMRPlate2RunMsg = "等待工作完成";

                        this.nextAMRPlate2Step = AMRPlateSteps.AMRPlate_WaitWorkStart;
                        break;
                    }
            }
        }

        /// <summary>
        /// 树脂板下料
        /// </summary>
        private void BeamUnloadThread()
        {
            if (Def.IsNoHardware())
            {
                Thread.Sleep(1000);
            }

            plcClient.ReadPlcData(ref plcData);

            switch (this.nextAMRBeamStep)
            {
                case AMRBeamSteps.AMRBeam_WaitWorkStart:
                    {
                        AMRBeamRunMsg = "等待开始信号";
                        if (MesIsConnected())
                        {
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_WaitRequest;
                        }
                        break;
                    }
                case AMRBeamSteps.AMRBeam_WaitRequest:
                    {
                        AMRBeamRunMsg = "等待PLC发送请求";

                        if (Def.IsNoHardware())
                        {
                            this.nextAMRBeamStep = !amrtest3 ? AMRBeamSteps.AMRBeam_StartLoad : AMRBeamSteps.AMRBeam_StartUnload;
                            return;
                        }

                        if (!plcData.beamCartArrived && !plcData.beamAMRArrived &&
                            plcData.beamCartLoadASK)
                        {
                            MesPortTransferStateChange(3, "B", PortTransferState.ReadyToLoad, preBeamTransferState);
                            preBeamTransferState = PortTransferState.ReadyToLoad;
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_StartLoad;
                        }

                        if (plcData.beamCartArrived && !plcData.beamAMRArrived &&
                            plcData.beamCartUnloadASK)
                        {
                            MesBeamUnloadStation(3, "B", "");

                            MesPortTransferStateChange(3, "B", PortTransferState.ReadyToUnload, preBeamTransferState);
                            preBeamTransferState = PortTransferState.ReadyToUnload;


                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_StartUnload;
                        }

                        break;
                    }
                case AMRBeamSteps.AMRBeam_StartLoad:
                    {
                        AMRBeamRunMsg = "等待AMR到达树脂板工位";
                        if (Def.IsNoHardware() || plcData.beamAMRArrived)
                        {
                            MesPortTransferStateChange(3, "B", PortTransferState.TransferBlocked, preBeamTransferState);
                            preBeamTransferState = PortTransferState.TransferBlocked;
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_CartLoadFinish;
                        }
                        break;
                    }
                case AMRBeamSteps.AMRBeam_CartLoadFinish:
                    {
                        AMRBeamRunMsg = "等待树脂板小车上料完成";
                        if (Def.IsNoHardware() || plcData.beamCartArrived)
                        {
                            MesCartLoadComplete(3);

                            amrtest3 = true;
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_WorkEnd;
                        }
                        break;
                    }
                case AMRBeamSteps.AMRBeam_StartUnload:
                    {
                        AMRBeamRunMsg = "等待AMR到达树脂板工位";
                        if (Def.IsNoHardware() || plcData.beamAMRArrived)
                        {
                            MesPortTransferStateChange(3, "B", PortTransferState.TransferBlocked, preBeamTransferState);
                            preBeamTransferState = PortTransferState.TransferBlocked;
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_CartUnloadFinish;
                        }

                        break;
                    }
                case AMRBeamSteps.AMRBeam_CartUnloadFinish:
                    {
                        AMRBeamRunMsg = "等待树脂板小车下料完成";
                        if (!plcData.beamCartArrived && !plcData.beamAMRArrived)
                        {
                            MesCartUnloadComplete(3, "B");
                            amrtest3 = false;
                            this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_WorkEnd;
                        }
                        break;
                    }
                case AMRBeamSteps.AMRBeam_WorkEnd:
                    {
                        AMRBeamRunMsg = "等待工作完成";

                        this.nextAMRBeamStep = AMRBeamSteps.AMRBeam_WaitWorkStart;
                        break;
                    }
            }
        }


        #endregion

        #region PLC

        public bool PlcIsConnected()
        {
            return plcClient.IsConnected();
        }

        public string PlcIP()
        {
            return plcClient.IP;
        }

        public int PlcPort()
        {
            return plcClient.Port;
        }

        public bool PlcConnect(ref string error)
        {
            this.plcClient.Disconnect(ref error);

            S7Plc plcClient1 = new S7Plc(plcIp, plcPort);
            bool ok = plcClient1.Connect(ref error);

            plcClient = plcClient1;

            return ok;
        }

        public bool PlcDisConnect(ref string error)
        {
            return plcClient.Disconnect(ref error);
        }

        public bool PlcReadData(ref PlcData plcData)
        {
            return this.plcClient.ReadPlcData(ref plcData);
        }

        #endregion

        #region RFID

        public string RfidIP(int index)
        {
            index = index < 3 ? 0 : 1;
            return rfidIP[index];
        }

        public int RfidPort(int index)
        {
            index = index < 3 ? 0 : 1;
            return rfidPort[index];
        }

        public bool RfidConnect(int index)
        {
            if (Def.IsNoHardware())
            {
                return true;
            }


            index = index < 3 ? 0 : 1;
            return this.dTE104Client[index].Connect(rfidIP[index], rfidPort[index]);

        }

        public void RfidDisConnect(int index)
        {
            index = index < 3 ? 0 : 1;
            this.dTE104Client[index].DisConnect();
        }

        public bool RfidIsConnected(int index)
        {
            if (Def.IsNoHardware())
            {
                return true;
            }

            index = index < 3 ? 0 : 1;
            return this.dTE104Client[index].IsConnected();
        }

        public string RfidGetUID(int index)
        {
            if (Def.IsNoHardware())
            {
                return "";
            }


            if (index < 3)
            {
                index = index == 0 ? 1 : index == 1 ? 0 : 2;
                return dTE104Client[0].GetUID(index + 1);
            }
            else
            {
                return dTE104Client[1].GetUID(1);
            }
        }

        public bool RfidReadCarrierID(int index, out string data)
        {
            if (Def.IsNoHardware())
            {
                data = "TEST001";
                return true;
            }

            if (index <= 3)
            {
                return dTE104Client[0].ReadCarrierID(index, out data);
            }
            else
                return dTE104Client[1].ReadCarrierID(1, out data);
        }

        #endregion

        #region MES

        public bool MesIsConnected()
        {
            if (!mesEN)
                return true;

            return KingEQP.GetInstance().GetCommState() == _eCommState.Comm_Communicating;
        }

        //CEID = 1
        public void MesControlStateOffline()
        {
            if (!mesEN)
                return;
            KingEQP.GetInstance().KingeqOfflineState();
        }

        //CEID = 2
        public void MesControlStateLocal()
        {
            if (!mesEN)
                return;
            KingEQP.GetInstance().KingLocal();
        }

        //CEID = 3
        public void MesControlStateRemote()
        {
            if (!mesEN)
                return;
            KingEQP.GetInstance().KingRemote();
        }

        // CEID = 1601 用户登录
        public bool MesLogin(string userName, string passWord)
        {
            if (!mesEN)
                return true;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // loginId
            dic.Add(20, userName);
            // Password
            dic.Add(21, passWord);
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(1601);

            return true;
        }

        // CEID = 20 修改设备状态
        public void MesEquipmentStateChange(EquipmentState equipmentState)
        {
            if (!mesEN)
                return;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(9, ((int)equipmentState).ToString());
            dic.Add(19, ((int)prevEquipmentState).ToString());

            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(20);

            prevEquipmentState = equipmentState;
        }

        //CEID = 17 设置报警
        public bool MesSetAlarm(int aId)
        {
            if (!mesEN)
                return true;

            KingEQP.GetInstance().KingGetAlarmInfo(aId, out int icd, out string tx, out bool en);
            if (icd == -1)
            {
                return false;
            }

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(2, icd.ToString());
            dic.Add(22, tx);
            dic.Add(24, aId.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(17);

            return true;
        }

        // CEID = 18 清除报警
        public bool MesClearAlarm(int aId)
        {
            if (!mesEN)
                return true;
            KingEQP.GetInstance().KingGetAlarmInfo(aId, out int icd, out string tx, out bool en);
            if (icd == -1)
            {
                return false;
            }

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(2, icd.ToString());
            dic.Add(22, tx);
            dic.Add(24, aId.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(18);

            return true;
        }

        // CEID = 2001 晶托上料
        public bool MesPlateOnloadStation(string plateID, int port)
        {
            if (!mesEN)
                return true;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, "L");
            // plate id
            dic.Add(5508, plateID);

            return KingEQP.GetInstance().KingSetVariable(dic)
             && KingEQP.GetInstance().KingSetEvent(2001);
        }

        // CEID = 2003 晶托上料
        public bool MesPlateOnloadStation2(string plateID)
        {
            if (!mesEN)
                return true;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, "2");
            // port type
            dic.Add(5500, "L");
            // plate id
            dic.Add(5508, plateID);

            return KingEQP.GetInstance().KingSetVariable(dic)
             && KingEQP.GetInstance().KingSetEvent(2003);
        }


        // CEID = 2002 晶托读取RFID
        public bool MesPlateReadRFID1(string plateID)
        {
            if (!mesEN)
                return true;

            // RFIDTag
            var semion = new Semion(false);
            semion.GEMSetListItem(2);
            semion.GEMSetAsciiItem("A");
            semion.GEMSetAsciiItem("B");
            KingEQP.GetInstance().KingSetVariableList(5518, semion);

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);

            KingEQP.GetInstance().KingSetVariable(dic);

            return KingEQP.GetInstance().KingSetEvent(2002);
        }

        // CEID = 2004 晶托读取RFID
        public bool MesPlateReadRFID2(string plateID)
        {
            if (!mesEN)
                return true;

            // RFIDTag
            var semion = new Semion(false);
            semion.GEMSetListItem(2);
            semion.GEMSetAsciiItem("A");
            semion.GEMSetAsciiItem("B");
            KingEQP.GetInstance().KingSetVariableList(5518, semion);

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);

            KingEQP.GetInstance().KingSetVariable(dic);

            return KingEQP.GetInstance().KingSetEvent(2004);
        }

        // CEID = 2005 到达脱胶机
        public bool MesPlateArriveDemounterStation(string plateID, int demountState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6701, demountState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2005);

            return true;
        }

        //CEID = 2006
        public bool MesPlateArriveDemounter2Station(string plateID, int demountState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6701, demountState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2006);

            return true;
        }

        // CEID = 2007 离开脱胶机
        public bool MesPlateLeaveDemounterStation(string plateID, int demountState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6701, demountState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2007);

            return true;
        }

        //CEID = 2008
        public bool MesPlateLeaveDemounter2Station(string plateID, int demountState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6701, demountState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2008);

            return true;
        }

        // CEID = 2009 到达码垛机
        public bool MesPlateArrivePalletizingStation(string plateID, int palletizingState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6703, palletizingState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2009);

            return true;
        }

        // CEID = 2010 晶托读取RFID
        public bool MesPlateReadRFID3(string plateID)
        {
            if (!mesEN)
                return true;

            // RFIDTag
            var semion = new Semion(false);
            semion.GEMSetListItem(2);
            semion.GEMSetAsciiItem("A");
            semion.GEMSetAsciiItem("B");
            KingEQP.GetInstance().KingSetVariableList(5518, semion);

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);

            KingEQP.GetInstance().KingSetVariable(dic);

            return KingEQP.GetInstance().KingSetEvent(2010);
        }

        // CEID = 2011 离开码垛机
        public bool MesPlateLeavePalletizingStation(string plateID, int palletizingState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6703, palletizingState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2011);

            return true;
        }

        // CEID = 2012 到达铲胶机
        public bool MesPlateArriveRemoveGlueStation(string plateID, int removeState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6704, removeState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2012);

            return true;
        }

        // CEID = 2013 离开铲胶机
        public bool MesPlateLeaveRemoveGlueStation(string plateID, int removeState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6704, removeState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2013);

            return true;
        }

        // CEID = 2014 到达清洗机
        public bool MesPlateArriveCleaningStation(string plateID, int cleaningState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6705, cleaningState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2014);

            return true;
        }

        // CEID = 2015 离开清洗机
        public bool MesPlateLeaveCleaningStation(string plateID, int cleaningState)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);
            dic.Add(6705, cleaningState.ToString());
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(2015);

            return true;
        }

        // CEID = 5001 端口状态改变
        public bool MesPortTransferStateChange(int port, string portType, PortTransferState curTransferState, PortTransferState preTransferState)
        {
            if (!mesEN)
                return true;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, portType);
            dic.Add(39, ((int)curTransferState).ToString());
            dic.Add(41, ((int)preTransferState).ToString());

            return KingEQP.GetInstance().KingSetVariable(dic)
             && KingEQP.GetInstance().KingSetEvent(5501);
        }

        //CEID = 5002
        public bool MesPortAccessModeChange(int port, string portType, PortAccessMode curAccessMode)
        {
            if (!mesEN)
                return true;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, portType);
            dic.Add(40, ((int)curAccessMode).ToString());
            dic.Add(42, ((int)preAccessMode[port]).ToString());

            preAccessMode[port] = curAccessMode;

            return KingEQP.GetInstance().KingSetVariable(dic)
             && KingEQP.GetInstance().KingSetEvent(5002);
        }

        // CEID = 5003 小车上料完成
        public bool MesCartLoadComplete(int port, string protType = "L")
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, protType);

            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(5003);

            return true;
        }

        //CEID = 5004 小车下料完成
        public bool MesCartUnloadComplete(int port, string protType = "L")
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, protType);
            KingEQP.GetInstance().KingSetVariable(dic);

            KingEQP.GetInstance().KingSetEvent(5004);

            return true;
        }

        // CEID = 2017 树脂板下料
        public bool MesBeamUnloadStation(int port, string protType, string plateID)
        {
            if (!mesEN)
                return true;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            // port id
            dic.Add(5505, port.ToString());
            // port type
            dic.Add(5500, protType);
            dic.Add(5508, plateID);
            KingEQP.GetInstance().KingSetVariable(dic);

            KingEQP.GetInstance().KingSetEvent(2017);

            return true;
        }

        // CEID = 5518 晶托RFID数据写入
        public bool MesPlateWriteRFID(string plateID)
        {
            if (!mesEN)
                return true;

            // RFIDTag
            var semion = new Semion(false);
            semion.GEMSetListItem(2);
            semion.GEMSetAsciiItem(plateID);
            semion.GEMSetAsciiItem("");
            KingEQP.GetInstance().KingSetVariableList(5518, semion);

            Dictionary<int, string> dic = new Dictionary<int, string>();
            // plate id
            dic.Add(5508, plateID);

            KingEQP.GetInstance().KingSetVariable(dic);

            return KingEQP.GetInstance().KingSetEvent(2016);
        }

        //CEID = 1605 命令成功
        public void MesPlateRcmdSuccessful(string plateID)
        {
            if (!mesEN)
                return;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(5508, plateID);
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(1605);

            return;
        }

        // CEID = 1606 命令失败
        public void MesPlateRcmdFailed(string plateID)
        {
            if (!mesEN)
                return;

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(5508, plateID);
            KingEQP.GetInstance().KingSetVariable(dic);
            KingEQP.GetInstance().KingSetEvent(1606);

            return;
        }

        #endregion

    }
}
